package com.lizard.schedule.ui.activity;

import android.content.Intent;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.iflytek.cloud.RecognizerResult;
import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.ui.RecognizerDialogListener;
import com.lizard.schedule.R;
import com.lizard.schedule.consts.Const;
import com.lizard.schedule.log.ScheduleLog;
import com.lizard.schedule.manager.AccountManager;
import com.lizard.schedule.manager.ScheduleLocalIdGenerator;
import com.lizard.schedule.manager.ScheduleSyncManager;
import com.lizard.schedule.manager.msc.SpeechRecognizerManager;
import com.lizard.schedule.manager.msc.model.recognizerresult.ChineseWord;
import com.lizard.schedule.manager.msc.model.recognizerresult.Word;
import com.lizard.schedule.manager.observer.ObserverManager;
import com.lizard.schedule.net.http.request.bean.ScheduleSync.ScheduleSyncItem;
import com.lizard.schedule.persistence.db.bean.Schedule;
import com.lizard.schedule.persistence.db.table.ScheduleTbl;
import com.lizard.schedule.ui.activity.base.BaseActivity;
import com.lizard.schedule.ui.view.ItemView;
import com.lizard.schedule.ui.view.Titlebar;
import com.lizard.schedule.utils.JsonUtil;
import com.lizard.schedule.utils.RepeatScheduleUtil;
import com.lizard.schedule.utils.ScheduleUtil;
import com.lizard.schedule.utils.StatusBarUtil;
import com.lizard.schedule.utils.TimeUtil;
import com.lizard.schedule.utils.ToastUtil;
import com.lizard.schedule.wear.Sender;
import com.lizard.schedule.widget.DateTimePickerDialog;
import com.lizard.schedule.widget.ScheduleAlertDialog;

import java.util.Date;
import java.util.List;

/**
 * 新增/修改计划内容
 */
public class EditScheduleActivity extends BaseActivity implements View.OnClickListener {

    /**
     * 未提交的新增内容记忆时间
     */
    private final long LAST_UNSUBMITED_ADD_DATA_REMEMBER_TIME = TimeUtil.HOUR_MILLIS / 2;

    /**
     * 动作：新增计划
     */
    public static String ACTION_CREATE = "create";
    /**
     * 动作：修改计划
     */
    public static String ACTION_MODIFY = "modify";

    private final int REQ_REPEAT = 1;

    /**
     * 参数：原计划 (只有修改计划动作才传)
     */
    public static String EXTRA_ORIGINAL_SCHEDULE = "origin_schedule";
    private final String TAG = EditScheduleActivity.class.getSimpleName();
    /**
     * 动作类型
     */
    private String mAction = ACTION_CREATE;

    /**
     * 原计划(只有修改计划动作才有)
     */
    private Schedule mOriginalSchedule;

    /**
     * 时间
     */
    private EditText mCreateScheduleTime;

    /**
     * 文字内容
     */
    private EditText mCreateScheduleText;

    /**
     * 重复选项
     */
    private ItemView repeatItem;

    /**
     * 剩余字数
     */
    private TextView mWordCount;

    /**
     * 选择的计划时间
     */
    private long mScheduleTime;

    private Handler mHandler;

    /**
     * 选择的重复类型
     */
    private int mRepeat = ScheduleSyncItem.REPEAT_NONE;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mHandler = new Handler();

        setContentView(R.layout.a_edit_schedule);

        // 设置状态栏颜色
        StatusBarUtil.setStatusBarColor(this, R.color.schedule_blue);

        mAction = getIntent().getAction();
        mAction = mAction == null ? ACTION_CREATE : mAction;
        if (mAction.equals(ACTION_MODIFY)) {
            mOriginalSchedule = getIntent().getParcelableExtra(EXTRA_ORIGINAL_SCHEDULE);
            if (mOriginalSchedule == null) {
                finish();
            }
        }


        if(mOriginalSchedule != null){
            mRepeat = mOriginalSchedule.getRepeat();
            mScheduleTime = mOriginalSchedule.getBeginTime();

        }

        initView();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    private void initView() {
        initTitle();
        initTimeContent();
        initTextContent();
        initRepeat();
        findViewById(R.id.dictation).setOnClickListener(this);
    }

    /**
     * “重复”选项初始化
     */
    private void initRepeat(){
        repeatItem = (ItemView) findViewById(R.id.repeat);
        repeatItem.setOnClickListener(this);
        refreshRepeatRightTxt();
    }

    private void refreshRepeatRightTxt(){
        StringBuilder sb = new StringBuilder();
        if(mRepeat == ScheduleSyncItem.REPEAT_NONE) { // 无
            sb.append(getString(R.string.none));
        } else if(RepeatScheduleUtil.containRepeat(mRepeat, ScheduleSyncItem.REPEAT_SUNDAY)
                && RepeatScheduleUtil.containRepeat(mRepeat, ScheduleSyncItem.REPEAT_MONDAY)
                && RepeatScheduleUtil.containRepeat(mRepeat, ScheduleSyncItem.REPEAT_TUESDAY)
                && RepeatScheduleUtil.containRepeat(mRepeat, ScheduleSyncItem.REPEAT_WEDNESDAY)
                && RepeatScheduleUtil.containRepeat(mRepeat, ScheduleSyncItem.REPEAT_THURSDAY)
                && RepeatScheduleUtil.containRepeat(mRepeat, ScheduleSyncItem.REPEAT_FRIDAY)
                && RepeatScheduleUtil.containRepeat(mRepeat, ScheduleSyncItem.REPEAT_SATURDAY)){ // 每天
            sb.append(getString(R.string.everyday));
        } else{
            if(RepeatScheduleUtil.containRepeat(mRepeat, ScheduleSyncItem.REPEAT_MONDAY)){
                sb.append(" ").append(getString(R.string.monday));
            }
            if(RepeatScheduleUtil.containRepeat(mRepeat, ScheduleSyncItem.REPEAT_TUESDAY)){
                sb.append(" ").append(getString(R.string.tuesday));
            }
            if(RepeatScheduleUtil.containRepeat(mRepeat, ScheduleSyncItem.REPEAT_WEDNESDAY)){
                sb.append(" ").append(getString(R.string.wednesday));
            }
            if(RepeatScheduleUtil.containRepeat(mRepeat, ScheduleSyncItem.REPEAT_THURSDAY)){
                sb.append(" ").append(getString(R.string.thursday));
            }
            if(RepeatScheduleUtil.containRepeat(mRepeat, ScheduleSyncItem.REPEAT_FRIDAY)){
                sb.append(" ").append(getString(R.string.friday));
            }
            if(RepeatScheduleUtil.containRepeat(mRepeat, ScheduleSyncItem.REPEAT_SATURDAY)){
                sb.append(" ").append(getString(R.string.saturday));
            }
            if(RepeatScheduleUtil.containRepeat(mRepeat, ScheduleSyncItem.REPEAT_SUNDAY)){
                sb.append(" ").append(getString(R.string.sunday));
            }
        }
        repeatItem.setRightTxt(sb.toString());
    }

    /**
     * 标题栏UI初始化
     */
    private void initTitle() {
        Titlebar titlebar = (Titlebar) findViewById(R.id.title_bar);
        titlebar.setTitle(mAction.equals(ACTION_CREATE) ? R.string.create_schedule_title : R.string.edit_schedule);

        titlebar.setLeftBtnClk(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                back();
            }
        });

        titlebar.setRightBtnClk(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                submit();
            }
        });
    }

    /**
     * 时间栏UI初始化
     */
    private void initTimeContent() {

        // 初始时间
        if (mAction.equals(ACTION_CREATE)) {
            long period = System.currentTimeMillis() - AccountManager.getInstance().getLastAddScheduleUnsubmitBackTime();
            if (period >= 0 && period < LAST_UNSUBMITED_ADD_DATA_REMEMBER_TIME) {
                mScheduleTime = AccountManager.getInstance().getLastAddScheduleTimeForBack();
            }
        }
        if (mScheduleTime <= 0) {
            mScheduleTime = AccountManager.getInstance().getLastEditScheduleTime();
        }
        if (mScheduleTime <= 0) {
            mScheduleTime = TimeUtil.getTomorrowNoonTime();
        }


        mCreateScheduleTime = (EditText) findViewById(R.id.create_schedule_time);
        setCreateScheduleTime(mScheduleTime);
        mCreateScheduleTime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                //时间选择器
                new DateTimePickerDialog.Builder(EditScheduleActivity.this)
                        .setTime(mScheduleTime)
                        .setShowDateWheel(mRepeat == ScheduleSyncItem.REPEAT_NONE)
                        .setPositiveButton(new DateTimePickerDialog.OnClickListener() {
                            @Override
                            public void onSelectTime(String time) {
                                mScheduleTime = TimeUtil.transferToTimeMills(time);
                                setCreateScheduleTime(mScheduleTime);
                            }

                            @Override
                            public void onClick(View view) {

                            }
                        }).show();


            }
        });
    }

    /**
     * 文本框UI初始化
     */
    private void initTextContent() {
        mCreateScheduleText = (EditText) findViewById(R.id.create_schedule_text);
        mWordCount = (TextView) findViewById(R.id.word_count);
        mWordCount.setText(Const.SCHEDULE_TEXT_MAX_LENGTH + "");

        mCreateScheduleText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                mWordCount.setText(Const.SCHEDULE_TEXT_MAX_LENGTH - mCreateScheduleText.length() + "");
            }
        });

        if (mAction.equals(ACTION_CREATE)) {
            long period = System.currentTimeMillis() - AccountManager.getInstance().getLastAddScheduleUnsubmitBackTime();
            if (period >= 0 && period < LAST_UNSUBMITED_ADD_DATA_REMEMBER_TIME) {
                mCreateScheduleText.setText(AccountManager.getInstance().getLastAddScheduleContentForBack());
            }
        } else {
            if (mOriginalSchedule != null) {
                mCreateScheduleText.setText(mOriginalSchedule.getContentText());
            }
        }
    }

    /**
     * 设置时间显示
     *
     * @param time
     */
    private void setCreateScheduleTime(long time) {
        String content;
        if(mRepeat == ScheduleSyncItem.REPEAT_NONE){
            String dayNearBy = TimeUtil.getDayNearby(System.currentTimeMillis(), time);
            content = TimeUtil.transferToDateTime(time);
            if (!TextUtils.isEmpty(dayNearBy)) {
                content += "   (" + dayNearBy + ")";
            }
        } else{
            content = TimeUtil.transferToTime(time);
        }
        mCreateScheduleTime.setHint(content);
    }

    /**
     * 返回
     */
    private void back() {
        ScheduleUtil.hideSoftInput(this);

        if (mAction.equals(ACTION_CREATE)) {
            String text = mCreateScheduleText.getText().toString().trim();
            if (!TextUtils.isEmpty(text)) {
                // 保存未提交的内容到内存
                AccountManager.getInstance().setLastAddScheduleUnsubmitBackTime(System.currentTimeMillis());
                AccountManager.getInstance().setLastAddScheduleTimeForBack(mScheduleTime);
                AccountManager.getInstance().setLastAddScheduleContentForBack(text);
            }
        }
        finish();
    }

    /**
     * 提交
     */
    private void submit() {
        String text = mCreateScheduleText.getText().toString().trim();

        if (!checkText(text)) {
            return;
        }

        if(mRepeat != ScheduleSyncItem.REPEAT_NONE){
            // 重复的计划日期改为下一个最近发生的日期
            mScheduleTime = RepeatScheduleUtil.generateNextRepatBeginTime(mScheduleTime, System.currentTimeMillis(), mRepeat);
        }

        // 记录最近一次编辑的时间到缓存
        AccountManager.getInstance().setLastEditScheduleTime(mScheduleTime);

        if (mAction.equals(ACTION_CREATE)) {
            Schedule schedule = new Schedule(ScheduleLocalIdGenerator.getInstance().getLocalId(), text, Schedule.SERVER_ID_DEFAULT, mScheduleTime, Schedule.STATUS_UNFINISHED, false, false, mRepeat);
            // 数据库更新
            ScheduleTbl.getInstance().insert(AccountManager.getInstance().getmUsernameMD5L16(), schedule);

            // 通知界面修改了Schedule数据
            ObserverManager.getInstance().notifyUpdateScheduleToUis(schedule);

            // 后台同步
            ScheduleSyncManager.getInstance().sync(null);

            // wear同步
            Sender.sendSchedules();
        } else {

            if (mScheduleTime != mOriginalSchedule.getBeginTime()
                    || !text.equals(mOriginalSchedule.getContentText())
                    || mRepeat != mOriginalSchedule.getRepeat()) { // 有改动
                Schedule schedule = (Schedule) mOriginalSchedule.clone();
                schedule.setBeginTime(mScheduleTime);
                schedule.setContentText(text);
                schedule.setSubmited(false);
                schedule.setRepeat(mRepeat);

                // 数据库更新
                ScheduleTbl.getInstance().update(AccountManager.getInstance().getmUsernameMD5L16(), schedule);

                // 通知界面修改了Schedule数据
                ObserverManager.getInstance().notifyUpdateScheduleToUis(schedule);

                // 去同步
                ScheduleSyncManager.getInstance().sync(null);

                // wear同步
                Sender.sendSchedules();
            }
        }

        // 清空内存中添加计划返回时有未提交的编辑内容
        clearLastAddUnsubmitData();

        finish();
    }

    /**
     * 检查计划文本有效性并提示
     *
     * @param text
     * @return 检查是否通过
     */
    private boolean checkText(String text) {
        if (TextUtils.isEmpty(text)) {
            ToastUtil.showScheduleToastS(R.string.please_edit_your_schedule_text);
            return false;
        }

        if (text.length() > Const.SCHEDULE_TEXT_MAX_LENGTH) {
            String msgFormat = getString(R.string.schedule_input_error_text_size_limit);
            new ScheduleAlertDialog.Builder(this)
                    .setMessage(String.format(msgFormat, Const.SCHEDULE_TEXT_MAX_LENGTH, text.length()))
                    .setNegativeButton(R.string.confirm, null)
                    .show();
            return false;
        }

        return true;
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        back();
    }

    /**
     * 清空内存中添加计划返回时有未提交的编辑内容
     */
    private void clearLastAddUnsubmitData() {
        AccountManager.getInstance().setLastAddScheduleContentForBack(null);
        AccountManager.getInstance().setLastAddScheduleTimeForBack(0);
        AccountManager.getInstance().setLastAddScheduleUnsubmitBackTime(0);
    }

    /**
     * 语音听写
     */
    private void dictation() {
        SpeechRecognizerManager.getInstance().buildRecognizerDialog(this,
                new RecognizerDialogListener() {
                    @Override
                    public void onResult(RecognizerResult recognizerResult, boolean isLast) {

                        try {
                            com.lizard.schedule.manager.msc.model.recognizerresult.RecognizerResult result
                                    = JsonUtil.getGson().fromJson(recognizerResult.getResultString(), com.lizard.schedule.manager.msc.model.recognizerresult.RecognizerResult.class);
                            if (result == null) {
                                return;
                            }

                            List<Word> words = result.getWs();
                            if (words == null || words.size() <= 0) {
                                return;
                            }

                            String speechContent = "";
                            for (Word word : words) {
                                List<ChineseWord> chineseWords = word.getCw();
                                if (chineseWords == null || chineseWords.size() <= 0) {
                                    continue;
                                }

                                String content = chineseWords.get(0).getW();
                                content = content.trim();
                                if (!TextUtils.isEmpty(content)) {
                                    speechContent += content;
                                }
                            }

                            if (!TextUtils.isEmpty(speechContent)) {
                                final String fSpeechContent = speechContent;
                                mHandler.post(new Runnable() {
                                    @Override
                                    public void run() {
                                        insertDictationContent(fSpeechContent);
                                    }
                                });
                            }

                        } catch (Exception e) {
                            ScheduleLog.e(TAG, e.toString());
                        }
                    }

                    @Override
                    public void onError(SpeechError speechError) {

                    }
                }).show();
    }

    /**
     * 将听写内容插入文本输入框
     *
     * @param speechContent
     */
    private void insertDictationContent(String speechContent) {
        int index = mCreateScheduleText.getSelectionStart();//获取光标所在位置
        Editable edit = mCreateScheduleText.getEditableText();//获取EditText的文字
        if (index < 0 || index >= edit.length()) {
            edit.append(speechContent);
        } else {
            edit.insert(index, speechContent);//光标所在位置插入文字
        }
    }

    /**
     * 打开"重复"设置页
     */
    private void gotoRepeatSetting(){
        Intent intent = new Intent(this, RepeatSettingActivity.class);
        intent.putExtra(RepeatSettingActivity.EXTRA_REPEAT_TYPE, mRepeat);
        startActivityForResult(intent, REQ_REPEAT);
    }

    @Override
    public void onClick(View v) {
        if(v.getId() == R.id.dictation){
            dictation();
        } else if(v.getId() == R.id.repeat){
            gotoRepeatSetting();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(RESULT_OK == resultCode){
            if(REQ_REPEAT == requestCode){
                if(data != null){
                    mRepeat = data.getIntExtra(RepeatSettingActivity.BACK_EXTRA_REPEAT_TYPE, ScheduleSyncItem.REPEAT_NONE);
                    refreshRepeatRightTxt();
                    setCreateScheduleTime(mScheduleTime);
                }
            }
        }
    }
}
